import os
import re

from lxml import etree

from PageObjectRequests import base_url
from util import http_utils
from util.DataQuery.hzflowOperation import hzflowOperation
from util.pdfSplit.compress_pdf import CompressPdf
from util.pdfSplit.pdf_split import get_file_oss
from util.selenium.webdriver.common.by import By

from base.BaseMethod import BM
from util.DataQuery.DbTools import DbTools
from util.DataQuery.FormDataDecorator import FormDataDecorator
from util.g import g
from util.sys_dict import techSource


class WriteRDForm():
    form_btn_loc = (By.LINK_TEXT, '企业研究开发活动情况表')
    title_loc = (By.CSS_SELECTOR, 'h2.text-center')
    content_iframe_loc = (By.CSS_SELECTOR, "#innocomFrame")

    delete = False

    # 写代码时方便提示, 基本方法完成后删除
    def __init__(self, driver=None):
        self.driver = driver
        self.size = 2
        # 用于第一次录入该表单时获取已填写的数据
        self.flag = False
        setattr(g, self.class_name, list())

    @property
    def class_name(self):
        return self.__class__.__name__

    @FormDataDecorator
    def main(self, rd_id='', rd_name='', start_date='', end_date='',
             tech_fieldname='', tech_fieldlist="", tech_source='', ipr_ids='', ipn_ids='',
             rd_budget='', rd_spend1styear='', rd_spend2ndyear='', rd_spend3rdyear='',
             ooim='', cti='', pra='', oss_path=None):
        try:
            class_name = self.class_name
            li_list = getattr(g, class_name)
            # 获取 研发活动页面 url
            if not self.flag:
                # BM.click(driver=self.driver, ele_loc=self.form_btn_loc)
                ele = BM.get_ele(driver=self.driver, ele_loc=self.form_btn_loc, time=6)
                detail_url = ele.get_attribute("href")
                BM.get_cookie(driver=self.driver)
                if not g.all_optimized:
                    BM.switch_to_frame(driver=self.driver, ele_loc=self.content_iframe_loc)
                detail_url = detail_url if detail_url.startswith("https://") else \
                    base_url + (detail_url if detail_url.startswith("/") else "/" + detail_url)
            if not self.flag:
                # if self.flag if g.repetition else False:
                # 获取已上传研发活动记录
                res = None
                text = None
                self.flag = True
                while True:
                    if not res:
                        # 请求 研发活动列表页
                        res = http_utils.send_get(detail_url, driver=self.driver)
                    # 替换掉国网随机插入的字符串
                    random_insert_chars_p = ".*?([\r\n].[0-9a-zA-Z]{4,}[\r\n].).*?"
                    text = res.get("text")
                    res = re.findall(random_insert_chars_p, text, re.S)
                    for i in res:
                        text = text.replace(i, "")
                    tree = etree.HTML(text)
                    # 获取 已上传记录
                    tr_list = tree.xpath(
                        '//form[@id="DataEprProject_list"]//div[@class="tableRegionDivBody"]//tbody/tr')
                    for tr in tr_list:
                        rd_id_str = BM.get_first(tr.xpath("./td[2]/text()"))
                        rd_name_str = BM.get_first(tr.xpath("./td[3]/text()"))
                        sign_str = "{}:{}".format(rd_id_str, rd_name_str)
                        # print(sign_str)
                        li_list.append(sign_str)

                    # 匹配下一页 url
                    next_list = tree.xpath("//form[@id='DataEprProject_list']//div[@class='page']/ul/li[4]/a")
                    next_a = BM.get_first(next_list)
                    next_onclick = None if not next_a else next_a.attrib.get("onclick")
                    if not next_onclick:
                        break
                    else:
                        # 获取下一页url
                        next_url_pattern = """.*?setAttribute\(['|"]action['|"],'(.*?)'.*?"""
                        next_res = re.findall(next_url_pattern, next_onclick, re.S)
                        next_url = BM.get_first(next_res)
                        next_page_pattern = """.*?value=['|"](\d+)['|"];.*?"""
                        next_page_res = re.findall(next_page_pattern, next_onclick, re.S)
                        next_page = BM.get_first(next_page_res)
                        if not next_url or not next_page:
                            break
                        next_url = (base_url + next_url) if not next_url.startswith("https://") else next_url
                        query_data = {
                            "ec_i": "",
                            "DataEprProject_list_crd": "10",
                            "DataEprProject_list_p": next_page,
                            "DataEprProject_list_a_dataEprProject_pxmbh": "",
                            "DataEprProject_list_a_dataEprProject_pxmmc": "",
                            "DataEprProject_list_a_dataEprProject_pjsly": "",
                            "DataEprProject_list_a_dataEprProject_pjslyaText": "",
                            "DataEprProject_list_a_dataEprProject_pzscqbha": "",
                            "DataEprProject_list_a_dataEprProject_pqzsj": "",
                            "DataEprProject_list_a_dataEprProject_Pyfjfzzc": "",
                            "dataInnocomId": "",
                            "type": "",
                            "DataEprProject_list_rd": "10",
                        }
                        tree = etree.HTML(text)
                        query_data["ec_i"] = BM.get_first(tree.xpath(
                            "//input[@name='ec_i']/@value"))
                        query_data["DataEprProject_list_a_dataEprProject_pxmbh"] = BM.get_first(tree.xpath(
                            "//input[@name='DataEprProject_list_a_dataEprProject_pxmbh']/@value"))
                        query_data["DataEprProject_list_a_dataEprProject_pxmmc"] = BM.get_first(tree.xpath(
                            "//input[@name='DataEprProject_list_a_dataEprProject_pxmmc']/@value"))
                        query_data["DataEprProject_list_a_dataEprProject_pjsly"] = BM.get_first(tree.xpath(
                            "//input[@name='DataEprProject_list_a_dataEprProject_pjsly']/@value"))
                        query_data["DataEprProject_list_a_dataEprProject_pjslyaText"] = BM.get_first(tree.xpath(
                            "//input[@name='DataEprProject_list_a_dataEprProject_pjslyaText']/@value"))
                        query_data["DataEprProject_list_a_dataEprProject_pzscqbha"] = BM.get_first(tree.xpath(
                            "//input[@name='DataEprProject_list_a_dataEprProject_pzscqbha']/@value"))
                        query_data["DataEprProject_list_a_dataEprProject_pqzsj"] = BM.get_first(tree.xpath(
                            "//input[@name='DataEprProject_list_a_dataEprProject_pqzsj']/@value"))
                        query_data["DataEprProject_list_a_dataEprProject_Pyfjfzzc"] = BM.get_first(tree.xpath(
                            "//input[@name='DataEprProject_list_a_dataEprProject_Pyfjfzzc']/@value"))
                        query_data["dataInnocomId"] = BM.get_first(tree.xpath(
                            "//input[@name='dataInnocomId']/@value"))
                        query_data["type"] = BM.get_first(tree.xpath(
                            "//input[@name='type']/@value"))
                        res = http_utils.send_post(next_url, data=query_data, driver=self.driver)

            rd_id = str(rd_id).zfill(2)

            sign = "{}:{}".format("RD" + rd_id, rd_name)
            if sign in li_list:
                g.logger.info("{} 已存在".format(sign))
                return
            # 获取研发活动新增页面
            add_url = "https://gqqy.chinatorch.org.cn/xonlinereport/inforeport/DataInnocom/addDataEprProject.do"
            add_res = http_utils.send_post(url=add_url, driver=self.driver)
            token = add_res.get("token")
            text = add_res.get("text")

            save_url = "https://gqqy.chinatorch.org.cn/xonlinereport/inforeport/DataInnocom/saveOrUpdateDataEprProject.do"
            rd_spend1styear = float(rd_spend1styear)
            rd_spend2ndyear = float(rd_spend2ndyear)
            rd_spend3rdyear = float(rd_spend3rdyear)
            total:float = 0.00
            total += rd_spend1styear if rd_spend1styear else 0
            total += rd_spend2ndyear if rd_spend2ndyear else 0
            total += rd_spend3rdyear if rd_spend3rdyear else 0
            rd_budget = float(rd_budget)
            data = {
                "dataEprProject.id": "",
                "dataInnocom.id": "",
                "dataInnocomId": "",
                "dataEprProject.dataId": "",
                "dataEprProject.entId": "",
                "dataEprProject.createDate": "",
                "struts.token.name": "token",
                "token": token,
                "dataEprProject.Pxmbh": rd_id,
                "dataEprProject.Pxmmc": rd_name,
                "dataEprProject.Pqzsj": start_date,
                "dataEprProject.Pjssj": end_date,
                # 技术领域
                "dataEprProject.Pjslya": techSource.get(tech_source),
                # key 相同的 参数可以使用列表传递
                "dataEprProject.Pzscqbha": ",".join([]),
                "__multiselect_dataEprProject.Pzscqbha": "",
                "dataEprProject.Pyfjfzys": str(round(rd_budget, 2)),
                "dataEprProject.Pyfjfzzc": str(round(total, 2)),
                "dataEprProject.Pyfzc3": str(rd_spend1styear),
                "dataEprProject.Pyfzc2": str(rd_spend2ndyear),
                "dataEprProject.Pyfzc1": str(rd_spend3rdyear),
                "dataEprProject.Plxmd": ooim,
                "dataEprProject.Phxjs": cti,
                "dataEprProject.Pqdcg": pra
            }
            domain_dict = hzflowOperation.get_domain_by_namelist(hitech_field_namelist=tech_fieldname)
            data["dataEprProject.Pjsly1"] = domain_dict.get("domain1")
            data["dataEprProject.Pjsly2"] = domain_dict.get("domain2")
            data["dataEprProject.Pjsly3"] = domain_dict.get("domain3")
            value = list()
            if ipr_ids:
                # 先从数据库里面查一下 ipr_ids 对应的 ip 是不是都有
                ipr_sql = """
                select * from hitech.ent_res_ipr where co_id={} and year={} and ipr_id in ({})
                """.format(g.co_id, g.year, ipr_ids)
                ipr_data = DbTools.get_hitech_record_by_sql(ipr_sql, model="all")
                ipr_ids = ",".join([str(i.get("ipr_id")) for i in ipr_data])
                # print("ipr_ids: {}".format(ipr_ids))
                for i in ipr_ids.split(","):
                    if i == "":
                        continue
                    if i == "0":
                        continue
                    if i.isdigit():
                        value.append("IP" + i.zfill(2))
            if ipn_ids:
                ipn_sql = """
                select * from hitech.ent_res_ipn where co_id={} and year={} and ipr_id in ({})
                """.format(g.co_id, g.year, ipn_ids)
                ipn_data = DbTools.get_hitech_record_by_sql(ipn_sql, model="all")
                ipn_ids = ",".join([str(i.get("ipr_id")) for i in ipn_data])
                for n in ipn_ids.split(","):
                    if n == "":
                        continue
                    if n == "0":
                        continue
                    if n.isdigit():
                        nstr = "NIP" + n.zfill(2)
                        value.append(nstr)

            data["dataEprProject.Pzscqbha"] = (",".join(value))

            # 获取页面参数
            dataEprProject_id_pattern = '.*?"dataEprProject.id".*?value="(.*?)".*?'
            dataEprProject_id_res = re.findall(dataEprProject_id_pattern, text, re.S)
            data["dataEprProject.id"] = "".join(dataEprProject_id_res)
            dataInnocom_id_pattern = '.*?"dataInnocom.id".*?value="(.*?)".*?'
            dataInnocom_id_res = re.findall(dataInnocom_id_pattern, text, re.S)
            data["dataInnocom.id"] = "".join(dataInnocom_id_res)
            dataInnocomId_pattern = '.*?"dataInnocomId".*?value="(.*?)".*?'
            dataInnocomId_res = re.findall(dataInnocomId_pattern, text, re.S)
            data["dataInnocomId"] = "".join(dataInnocomId_res)
            dataEprProject_dataId_pattern = '.*?"dataEprProject.dataId".*?value="(.*?)".*?'
            dataEprProject_dataId_res = re.findall(dataEprProject_dataId_pattern, text, re.S)
            data["dataEprProject.dataId"] = "".join(dataEprProject_dataId_res)
            dataEprProject_entId_pattern = '.*?"dataEprProject.entId".*?value="(.*?)".*?'
            dataEprProject_entId_res = re.findall(dataEprProject_entId_pattern, text, re.S)
            data["dataEprProject.entId"] = "".join(dataEprProject_entId_res)
            dataEprProject_createDate_pattern = '.*?"dataEprProject.createDate".*?value="(.*?)".*?'
            dataEprProject_createDate_res = re.findall(dataEprProject_createDate_pattern, text, re.S)
            data["dataEprProject.createDate"] = BM.get_first(dataEprProject_createDate_res)
            print("dataEprProject_createDate_res: {}".format(dataEprProject_createDate_res))
            mdp_pattern = '.*?"__multiselect_dataEprProject.Pzscqbha".*?value="(.*?)".*?'
            mdp_res = re.findall(mdp_pattern, text, re.S)
            data["__multiselect_dataEprProject.Pzscqbha"] = "".join(mdp_res)

            file_path = None
            if g.need_file:
                if oss_path:
                    file_path = BM.get_material_path() + "\\RD\\rd_{}.pdf".format(rd_id)
                    is_exist = BM.check_file(file_path=file_path, size=self.size)
                    if is_exist is False:
                        oss_file = get_file_oss(oss_path=oss_path, local_path=file_path + ".pdf")
                        BM.wait_file(file_path=oss_file)
                        CompressPdf(file_path=oss_file, max_size=self.size).compress()
                        BM.wait_file(file_path=file_path)

            res = http_utils.send_post(url=save_url, data=data, file_path=file_path,
                                       file_key="upload", driver=self.driver)
            text = res.get("text")
            message = res.get("message")
            g.logger.info("企业研究开发活动情况表（{}）上传结果: {}".format(sign, message))
            if u"成功" in message:
                li_list.append(sign)
            else:
                if u"未登录或登录超时" in text:
                    self.driver.quit()
                    os._exit(0)
                g.logger.info("text: {}".format(text))

        except Exception as err:
            msg = "error: {} file: {} lines: {}".format(
                err, err.__traceback__.tb_frame.f_globals["__file__"],
                err.__traceback__.tb_lineno)
            g.logger.error(msg)
            raise Exception(msg)
